package com.project.controller;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.project.common.ImageUtil;
import com.project.common.ServerResponse;
import com.project.dao.IpAddressMapper;
import com.project.pojo.IpAddress;
import com.project.pojo.PageQueryBean;
import com.project.pojo.StudentList;
import com.project.pojo.User;
import com.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.print.attribute.standard.NumberUp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 此请求每个方法都要校验是否已经登陆,注意: 校验方式是请求时携带一个token. 登录成功时给的token. 存在了redis里面
 *
 * @return 返回数据
 */

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private IpAddressMapper ipAddressMapper;

    @Autowired
    private UserService userService;

    @RequestMapping("/testdatatables")
    public String test(){
        return "testdatatables";
    }

    @RequestMapping(value = "/home")
    public String home() {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return "redirect:login";
        } else if (currentUser.getRole() == 1) {
            return "teaHome";
        }
        return "home";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/userinfo")
    @ResponseBody
    public ServerResponse<User> getUserInfo() {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return ServerResponse.createByErrorMessage("请先登录!");
        }
        return ServerResponse.createBySuccess("获取用户信息成功!", currentUser);
    }

    @RequestMapping("/position")
    public void getUserPosition(HttpServletRequest request) {
        String lnt = request.getParameter("lng");
        String lat = request.getParameter("lat");
        String acc = request.getParameter("accuracy");
        IpAddress ia = new IpAddress();
        ia.setIpAddress(lnt + "," + lat + "," + acc);
        ipAddressMapper.insert(ia);
    }
//    @RequestMapping()
//    @ResponseBody
//    public ServerResponse<User> getUserInfoById(HttpServletRequest request){
//        User currentUser = getCurrentUser();
//        if (currentUser == null || currentUser.getId() == null) {
//            return ServerResponse.createByErrorMessage("请先登录!");
//        }
//        int i = Integer.parseInt(request.getParameter("id"));
//        User user = userService.findUserByUserId(i);
//        return null;
//    }

    /**
     * 更新个人信息接口
     *
     * @param user
     * @return
     */
    @RequestMapping("/updateInfo")
    @ResponseBody
    public ServerResponse<User> updateUserInfo(@RequestBody User user) {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return ServerResponse.createByErrorMessage("请先登录!");
        }
        ServerResponse<User> response = userService.updateUserInfo(user);
        return response;
    }

    @RequestMapping("/modifyData")
    public String modifyData() {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return "login";
        }
        return "modifyData";
    }

    @RequestMapping(value = "/uploadHeadImg", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    @ResponseBody
    public ServerResponse<String> uploadHeadImg(
            @RequestParam(value = "avatar_file", required = false) MultipartFile avatar_file,
            String avatar_src, String avatar_data, HttpServletRequest request) {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return ServerResponse.createByErrorMessage("请先登录!");
        }
        if (!avatar_file.getContentType().contains("image")) {
            return ServerResponse.createByErrorMessage("请选择正确的图片格式!");
        }
        JsonParser parse = new JsonParser();
        JsonObject json = (JsonObject) parse.parse(avatar_data);
        int x = Math.round(json.get("x").getAsFloat());
        int y = Math.round(json.get("y").getAsFloat());
        int w = Math.round(json.get("width").getAsFloat());
        int h = Math.round(json.get("height").getAsFloat());
        int r = Math.round(json.get("rotate").getAsFloat());
        File file;
        ServerResponse response;
        try {
            file = new File("d:/image", currentUser.getToken() + ".png");
            InputStream is = avatar_file.getInputStream();
            ImageUtil.cut(is, file, x, y, w, h);
            response = userService.uploadHeadImg(file, currentUser.getId());
            file.delete();
        } catch (IOException e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("失败!");
        }
        return response;
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        User user = getCurrentUser();
        userService.logout(user.getToken());
        request.getSession().invalidate();
        delAllCookie(request, response);
        return "login";
    }


    //todo 下面方法都要验证权限.

    @RequestMapping(value = "/teaHome")
    public String teaHome(HttpServletRequest request) {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return "login";
        }
        if (currentUser.getRole() != 1) {
            return "login";
        }
        //todo 查询当前教师的班级.根据教师的班级进行分页查询  (还没教师表)
        return "teaHome";
    }


    @RequestMapping(value = "/myStudentList",method = RequestMethod.GET)
    @ResponseBody
    public PageQueryBean myAllStudent(HttpServletRequest request) {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return null;
        }
        if (currentUser.getRole() != 1) {
            return null;
        }
        List<User> list = userService.myAllStudent(currentUser);
        if (list == null) {
            log.warn("UserController:115 警告!");
        }
        PageQueryBean pageQueryBean = new PageQueryBean();
        pageQueryBean.setItems(list);
        pageQueryBean.setTotalRows(list.size());
        return pageQueryBean;
    }


    /**
     * 权限:教师和管理员
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/delStu")
    @ResponseBody
    public ServerResponse delStu(HttpServletRequest request) {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return ServerResponse.createByErrorMessage("请先登录!");
        }
        if (currentUser.getRole() != 1) {
            return ServerResponse.createByErrorMessage("别这样~");
        }
        int i = userService.deleteUserById(Integer.parseInt(request.getParameter("id")));
        if (i != 1) {
            ServerResponse.createByErrorMessage("删除失败,请及时联系管理员!");
        }
        return ServerResponse.createBySuccess("删除成功!");
    }

    /**
     * 教师和管理员
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/updateStu")
    @ResponseBody
    public ServerResponse updateStu(User user) {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return ServerResponse.createByErrorMessage("请先登录!");
        }
        if (user == null) {
            return ServerResponse.createByErrorMessage("操作有误!");
        }
        if (getCurrentUser() == null) {
            return ServerResponse.createByErrorMessage("请先登录!");
        }
        int i = userService.updateStuInfo(user);
        if (i != 1) {
            ServerResponse.createByErrorMessage("修改失败!");
        }
        return ServerResponse.createByErrorMessage("修改成功!");
    }

    /**
     * 权限:教师和管理员
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/addStu")
    @ResponseBody
    public ServerResponse addStu(HttpServletRequest request) {
        User currentUser = getCurrentUser();
        if (currentUser == null || currentUser.getId() == null) {
            return ServerResponse.createByErrorMessage("请先登录!");
        }
        return null;
    }
}